package com.ruoyi.backend.controller;

import com.ruoyi.backend.enumClass.sseVoEnum;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Api(tags = "长连接相关接口")
@Slf4j
@RequestMapping("/backend/sse")
@RestController
public class SseController {

    final static ConcurrentHashMap<String,SseEmitter> SseMap = new ConcurrentHashMap<>();
        /**
     * 获取SSE连接
     *
     * @return SseEmitter SSE连接实例
     */
    @GetMapping(path = "/getSseEmitter",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter getSseEmitter() {
        String token = SecurityUtils.getLoginUser().getToken();
        if (SseMap.containsKey(token)){
            SseEmitter sseEmitter = SseMap.get(token);
            try {
                sseEmitter.send(sseVoEnum.LINK_SUCCESS);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return sseEmitter;
        }else{
            // 创建新的SSE连接，设置超时时间为1小时
            SseEmitter sseEmitter = new SseEmitter(60 * 60 * 1000L);
            SseMap.put(token,sseEmitter);
            try {
                sseEmitter.send(sseVoEnum.LINK_SUCCESS);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 注册连接完成回调事件
            sseEmitter.onCompletion(() -> {
                SseMap.remove(token);
            });

            // 注册连接超时回调事件
            sseEmitter.onTimeout(() -> {
                SseMap.remove(token);
            });

            // 注册连接错误回调事件
            sseEmitter.onError((throwable) -> {
                    SseMap.remove(token);
            });
            return sseEmitter;
        }
    }



}
